<template>
  <div class="app-container" style="padding:8px 0 10px 0;height: calc(100% - 50px);">
    <el-form ref="showParamsRef" style="" :inline="true" :model="queryParams" label-width="90px">
      <el-row style="flex-wrap:nowrap; margin-top: -10px;margin-bottom: -15px;justify-content: space-between;">
        <el-form-item class="header-lable" style="flex-direction: column;" label="长/临:" prop="repeatIncaditor">
          <el-radio-group v-model="queryParams.repeatIncaditor" @change="handleQuery">
            <el-radio-button label="全部" value=""/>
            <template v-for="(tag, index) in dictDataMap['order_type']">
              <el-radio-button :label="tag.dictLabel" :value="tag.dictValue"/>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="flex-direction: column;" label="医嘱状态:" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" class="width-120"
                     placeholder="请选择" @change="handleQuery">
            <el-option label="全部" value="22"></el-option>
            <el-option v-for=" dict in dictDataMap['order_status'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="flex-direction: column;" label="医嘱内容:" prop="orderText">
          <el-input v-model="queryParams.orderText" class="width-120" placeholder="请输入医嘱内容"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item style="flex-direction: column; width: 200px;" label="下达时间:" prop="admissionTime">
          <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                          range-separator="-" start-placeholder="开始日期" type="daterange"
                          @change="admissionTimeChange"></el-date-picker>
        </el-form-item>
        <el-form-item class="header-lable-botton-box">
          <el-button class="mb5 header-button-primary" type="primary" @click="handleQuery">
            <template #icon>
              <i-ep-search/>
            </template>
            刷新
          </el-button>
          <el-button class="mb5 header-button-warning" type="primary" @click="emrURL">
            <template #icon>
              <i-ep-edit/>
            </template>
            写病历
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <div class="app-container-table-list">
      <el-row class="mb5">
        <el-col :span="15">
          <el-form-item label="西药发药药房" prop="implementDept"
                        style="width: 200px;display:inline-flex;margin-left:12px">
            <el-select v-model="autoForm.storageId"
                       placeholder="请输入发药药房">
              <el-option v-for="drugVsDept in drugVsDeptList" :key="drugVsDept.id"
                         :label="drugVsDept.storageName" :value="drugVsDept.id"></el-option>
            </el-select>
          </el-form-item>
          <el-tooltip class="box-item" content="开医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" plain round type="primary" @click="handleAddOrder">
              <template #icon>
                <i-ep-plus/>
              </template>
              开医嘱(F1)
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="模板引用" effect="dark" placement="bottom">
            <el-button color="#8888ff" plain round
                       @click="templateOpen">
              <svg-icon class="mr5" icon-class="template"/>
              模板引用
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="保存医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" round type="primary" @click="saveOrder">
              <svg-icon class="mr5" icon-class="save"/>
              保存医嘱(F8)
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="传输" effect="dark" placement="bottom">
            <el-button class="ml10" round type="success" @click="transmitOrder">
              <svg-icon class="mr5" icon-class="transmitOrder"/>
              传输
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="作废" effect="dark" placement="bottom">
            <el-button class="ml10" round type="warning" @click="cancelOrder">
              <svg-icon class="mr5" icon-class="cancel"/>
              作废
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="停止【校对】状态的【长期】医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" round type="danger" @click="stopOrder">
              <svg-icon class="mr5" icon-class="stop"/>
              长嘱停止
            </el-button>
          </el-tooltip>
        </el-col>
        <el-col :span="9">
          <div style="text-align: right;margin-right: 25px">
            <el-tooltip class="box-item" content="开检查" effect="dark" placement="bottom">
              <el-button class="ml10" color="#626aef" round @click="handleAddExam">
                <svg-icon :icon-class="'exam'" class="mr5"/>
                开检查(F2)
              </el-button>
            </el-tooltip>
            <el-tooltip class="box-item" content="开检验" effect="dark" placement="bottom">
              <el-button class="ml10" round type="success" @click="handleAddLab">
                <svg-icon :icon-class="'lab'" class="mr5"/>
                开检验(F3)
              </el-button>
            </el-tooltip>
            <el-tooltip class="box-item" content="开中草药" effect="dark" placement="bottom">
              <el-button class="ml10" plain round type="warning" @click="handleAddDrugChineseHerbalMedicine">
                <svg-icon :icon-class="'drugChineseHerbalMedicine'" class="mr5"/>
                开中草药(F4)
              </el-button>
            </el-tooltip>
            <el-tooltip class="box-item" content="手术申请" effect="dark" placement="bottom">
              <el-button class="ml10" plain round type="danger" @click="handleAddSurgery">
                <svg-icon :icon-class="'operatingRoom'" class="mr5"/>
                手术申请(F5)
              </el-button>
            </el-tooltip>
          </div>

        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-table v-adaptive="272" :border="true" :data="form.orderList" :header-cell-style="$headerCellStyle"
                  :stripe="true"
                  class="yizhu-table"
                  highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="40"/>
          <el-table-column :align="'center'" fixed="left" label="医嘱状态" prop="orderStatus" width="90">
            <template #default="scope">
              <template v-for="(tag, index) in dictDataMap['order_status']">
                <template v-if="scope.row.orderStatus.includes(tag.dictValue)">
                  <el-button v-if="!tag.cssClass" :class="scope.row.orderStatus === '1' ? 'mb25': ''"
                             :type="tag.listClass"
                             style="border: 1px #000000 solid;margin-bottom:0;">{{ tag.dictLabel }}
                  </el-button>
                  <el-tooltip v-else
                              :content="scope.row.orderStatus === '8'? '驳回原因：'+scope.row.rebuteRemarks :''"
                              class="box-item"
                              effect="dark"
                              placement="top">
                    <el-button :class="scope.row.orderStatus === '1' ? 'mb25': ''"
                               :color="tag.cssClass"
                               style="border: 1px #000000 solid;margin-bottom:0">{{ tag.dictLabel }}
                    </el-button>
                  </el-tooltip>

                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="left" label="操作"
                           width="50">
            <template #default="scope">
              <el-tooltip v-if="scope.row.orderStatus === '1' || scope.row.orderStatus === '8'"
                          class="box-item" content="删除" effect="dark"
                          placement="right">
                <el-button circle class="mb20" style="margin-bottom:0" type="danger"
                           @click="handleDelete(scope.$index, scope.row)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" fixed="left" label="组号" prop="groupNumber" width="70">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.groupNumber'"
                            :rules="rules.groupNumber" class="table-form-margin">
                <el-input v-model="scope.row.groupNumber"
                          v-keyupEnter="{ orderStatus: scope.row.orderStatus,index: scope.$index, name: 'groupNumber' }"
                          :disabled="scope.row.groupNumberDisabled"
                          class="groupNumber"
                          clearable prop="groupNumber"
                          type="number"
                          @blur="groupNumberBlur($event, scope.$index, scope.row)"></el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow">{{
                  scope.row.groupNumber
                }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" fixed="left" label="是否计价" prop="billingAttr" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow">
                <el-select v-model="scope.row.billingAttr"
                           v-keyupEnter="{index: scope.$index, name: 'billingAttr' }"
                           :disabled="scope.row.billingAttrDisabled"
                           class="width-120"
                           placeholder="请选择是否计价">
                  <el-option v-for="dict in dictDataMap['billing_attr']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['billing_attr']"
                                                              :value="scope.row.billingAttr"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" fixed="left" label="下达时间" prop="createTime" width="170">
            <template #default="scope">
              <template v-if="scope.row.isShow">
                <el-date-picker v-model="scope.row.createTime"
                                :disabled="scope.row.createTimeDisabled"
                                class=" mb25"
                                style="width: 100%;margin-bottom:0"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                @change="createTimeChange($event, scope.$index, scope.row)"></el-date-picker>
              </template>
              <span v-else>{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" fixed="left" label="医嘱类别" prop="orderClass" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow">
                <el-select v-model="scope.row.orderClass"
                           v-keyupEnter="{index: scope.$index, name: 'orderClass' }"
                           :disabled="scope.row.orderClassDisabled"
                           class="width-120"
                           placeholder="请选择医嘱类别"
                           @change="orderClassChange($event, scope.$index, scope.row)">
                  <el-option v-for="dict in dictDataMap['new_order_type']" :key="dict.dictValue"
                             :disabled="dict.dictValue ==='4'|| dict.dictValue ==='5'"
                             :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['new_order_type']"
                                                              :value="scope.row.orderClass"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" fixed="left" label="长/临" prop="repeatIncaditor" width="80">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow">
                <el-select v-model="scope.row.repeatIncaditor"
                           v-keyupEnter="{index: scope.$index, name: 'repeatIncaditor' }"
                           :disabled="scope.row.repeatIncaditorDisabled"
                           class="width-120"
                           placeholder="请选择长/临"
                           @change="repeatIncaditorChange($event, scope.$index, scope.row)">
                  <el-option v-for="dict in dictDataMap['order_type']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['order_type']"
                                                              :value="scope.row.repeatIncaditor"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true" fixed="left"
                           label="医嘱内容"
                           prop="orderText"
                           width="220">
            <template #default="scope">
              <template v-if="scope.row.isShow">
                <el-form-item :prop="'orderList.' + scope.$index + '.orderText'"
                              :rules="rules.orderText"
                              class="table-form-margin">
                     <span
                       v-if="['4', '5'].includes(scope.row.orderClass)">
                     {{ scope.row.orderText }}
                 </span>
                  <span v-else-if="scope.row.isShow && scope.row.orderClass==='3'">
                                    <el-input v-model="scope.row.orderText"/>
                                </span>
                  <automatic-completion v-else-if="scope.row.orderClass==='1' || scope.row.orderClass==='2' || scope.row.orderClass==='6'"
                                        :ref="(el:any) => setItemAutomaticRef(el, scope.$index)" :dict-array="dictArray"
                                        :right-div-show-type="scope.row.orderClass === '1' || scope.row.orderClass === '6' ? 'westernMedicine' :''"
                                        :table-body-list="tableBodyList" :table-head-list="tableHeadList"
                                        :title="itemTitle"
                                        :width="950"
                                        style="width: 100%;"
                                        @itemNameInput="itemNameInput($event, scope.$index, scope.row)"
                                        @rowClick="rowClick($event, scope.$index, scope.row)"/>
                </el-form-item>
              </template>
              <template v-else>{{ scope.row.groupNumberStyle }}<span class="ml5">{{
                  scope.row.orderText
                }}</span></template>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" header-align="center" label="途径" prop="channel" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.channel'"
                            :rules="rules.channel" class="table-form-margin">
                <administration-index v-keyupEnter="{index: scope.$index, name: 'channel' }"
                                      :disabled="scope.row.channelDisabled"
                                      :placeholder="'请选择途径'" :value="scope.row.channel"
                                      style="width: 100%"
                                      @administrationInfoChange="administrationInfoChange($event, scope.$index, scope.row)"/>
              </el-form-item>
              <span v-show="!scope.row.isShow">{{ scope.row.channelName }}
              <span v-if="scope.row.allergyResult"
                    :style="{color: scope.row.allergyResult!= '-' ?  '#ff0000' : '#159100',fontWeight:'bold'}"
                    class="ml5">({{
                  scope.row.allergyResult
                }})</span></span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" header-align="center" label="频次"
                           prop="performFreq" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.performFreq'"
                            :rules="rules.performFreq" class="table-form-margin">
                <perform-index ref="performIndex" v-keyupEnter="{index: scope.$index, name: 'performFreq' }"
                               :disabled="scope.row.performFreqDisabled"
                               :placeholder="'请选择频次'" :value="scope.row.performFreq"
                               style="width: 100%"
                               @performFreqInfoChange="performFreqInfoChange($event, scope.$index, scope.row)"/>
              </el-form-item>
              <span v-show="!scope.row.isShow">{{ scope.row.performFreqName }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="执行时间" prop="nursePerformTime" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.nursePerformTime'"
                            :rules="rules.nursePerformTime" class="table-form-margin">
                <el-input v-model="scope.row.nursePerformTime"
                          v-keyupEnter="{index: scope.$index, name: 'nursePerformTime' }"
                          :disabled="scope.row.nursePerformTimeDisabled"
                          class="input-mr"
                          clearable
                          @blur="nursePerformTimeBlur($event, scope.$index, scope.row)">
                </el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow">{{ scope.row.nursePerformTime }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="单次用量" prop="numSingle" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.numSingle'"
                            :rules="rules.numSingle" class="table-form-margin">
                <el-input v-model="scope.row.numSingle"
                          v-keyupEnter="{index: scope.$index, name: 'numSingle' }"
                          :disabled="scope.row.numSingleDisabled"
                          class="input-mr"
                          clearable
                          @blur="inputBlur(scope.$index)">
                  <template #append>{{ scope.row.minUnitsName }}</template>
                </el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow"
                    style="margin-left: -15px"> {{ parseFloat(scope.row.numSingle).toFixed(2) }}<dict-data-tag
                :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                style="margin: -23px -20px 0px 35px"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="单次剂量" prop="singleDosage" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.singleDosage'"
                            :rules="rules.singleDosage" class="table-form-margin">
                <el-input v-model="scope.row.singleDosage"
                          v-keyupEnter="{index: scope.$index, name: 'singleDosage' }"
                          :disabled="scope.row.singleDosageDisabled" class="input-mr" clearable
                          @blur="inputBlur(scope.$index)">
                  <template #append>{{ scope.row.doseUnitsName }}</template>
                </el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow"
                    style="margin-left: -15px"> {{ parseFloat(scope.row.singleDosage).toFixed(2) }}<dict-data-tag
                :options="dictDataMap['dose_unit']" :value="scope.row.doseUnits"
                style="margin: -23px -20px 0px 35px"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="数量" prop="sumNum" width="90">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.sumNum'"
                            :rules="rules.sumNum" class="table-form-margin">
                <el-input v-model="scope.row.sumNum" v-keyupEnter="{index: scope.$index, name: 'sumNum' }"
                          :disabled="scope.row.sumNumDisabled"
                          class="input-mr"
                          clearable>
                  <template #append>{{ scope.row.unitsName }}</template>
                </el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow"
                    :style="!scope.row.packageUnits ?'margin-left: -14px':'margin-left: -15px'"> {{
                  scope.row.sumNum
                }}
                <!--                            {{ scope.row.unitsName }}-->
                                                        <dict-data-tag
                                                          v-if="scope.row.packageUnits"
                                                          :options="dictDataMap['spec_unit']" :value="scope.row.unit"
                                                          style="margin: -23px -20px 0px 35px"/>
                            </span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="首日是否摆药" prop="firstDayIsDisp" width="90">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow">
                <el-select v-model="scope.row.firstDayIsDisp"
                           v-keyupEnter="{index: scope.$index, name: 'firstDayIsDisp' }"
                           :disabled="scope.row.firstDayIsDispDisabled"
                           class="width-120"
                           placeholder="请选择首日是否摆药"
                           @change="firstDayIsDispChange($event, scope.$index, scope.row)">
                  <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['sys_yes_no']"
                                                              :value="scope.row.firstDayIsDisp"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="首日摆药数量" prop="firstDayDrugDispAmount" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :rules="rules.numSingle" class="table-form-margin">
                <el-input v-model="scope.row.firstDayDrugDispAmount"
                          v-keyupEnter="{index: scope.$index, name: 'firstDayDrugDispAmount' }"
                          :disabled="scope.row.firstDayDrugDispAmountDisabled"
                          class="input-mr"
                          clearable
                          @blur="inputBlur(scope.$index)">
                  <template #append>{{ scope.row.minUnitsName }}</template>
                </el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow" style="margin-left: -15px"> {{
                  scope.row.firstDayDrugDispAmount
                }}<dict-data-tag
                  :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                  style="margin: -23px -20px 0px 35px"/></span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow">
                <el-select v-model="scope.row.dripSpeed"
                           v-keyupEnter="{index: scope.$index, name: 'dripSpeed' }"
                           :disabled="scope.row.dripSpeedDisabled"
                           class="width-120"
                           clearable
                           placeholder="请选择滴速"
                           @change="dripSpeedChange($event, scope.$index, scope.row)">
                  <el-option v-for="dict in dictDataMap['sys_drop_speed']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['sys_drop_speed']"
                                                              :value="scope.row.dripSpeed"/></span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="包装单位" :align="'center'" prop="packageUnits" width="100" /> -->
          <!--                <el-table-column label="库存量" :align="'center'" prop="quantityAndUnits" width="100">-->
          <!--                    <template #default="scope">-->
          <!--                        <div class="mb25"> {{ scope.row.quantityAndUnits }}</div>-->
          <!--                    </template>-->
          <!--                </el-table-column>-->
          <!--                <el-table-column label="已开预存数量" :align="'center'" prop="quantityAndUnits" width="80">-->
          <!--                    <template #default="scope">-->
          <!--                        <div class="mb25"> {{ scope.row.quantityAndUnits }}</div>-->
          <!--                    </template>-->
          <!--                </el-table-column>-->
          <!--                <el-table-column label="包装规格" :align="'center'" prop="packageSpec" width="100"/>-->

          <el-table-column :align="'center'" label="执行科室" prop="implementDept" width="100">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.implementDept'"
                            class="table-form-margin">
                <el-select v-model="scope.row.implementDept"
                           v-keyupEnter="{index: scope.$index, name: 'implementDept' }"
                           :disabled="scope.row.implementDeptDisabled" clearable
                           placeholder="请选择执行科室"
                           style="width: 100%;"
                           @change="deptChange($event, scope.$index, scope.row)">
                  <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName"
                             :value="item.deptId">
                  </el-option>
                </el-select>
                <!--                            <dept-list-->
                <!--                                v-model="scope.row.implementDept"-->
                <!--                                v-keyupEnter="{index: scope.$index, name: 'implementDept' }"-->
                <!--                                :dept-id="scope.row.implementDept"-->
                <!--                                :disabled="scope.row.implementDeptDisabled"-->
                <!--                                :org-id="userInfo.orgId"-->
                <!--                                :placeholder="'请选择执行科室'"-->
                <!--                                style="width: 100%"-->
                <!--                                @deptChange="deptChange($event, scope.$index, scope.row)"-->
                <!--                            />-->
              </el-form-item>
              <span v-show="!scope.row.isShow">{{ scope.row.implementDeptName }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="医嘱说明" prop="remarks" width="120">
            <template #default="scope">
              <el-form-item v-show="scope.row.isShow"
                            :prop="'orderList.' + scope.$index + '.remarks'"
                            class="table-form-margin">
                <el-input v-model="scope.row.remarks" v-keyupEnter="{index: scope.$index, name: 'remarks' }"
                          :disabled="scope.row.remarksDisabled"
                          class="input-mr"
                          clearable>
                </el-input>
              </el-form-item>
              <span v-show="!scope.row.isShow">{{ scope.row.remarks }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="开单医生" prop="applyUserName" width="90"/>
          <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="90"/>
          <el-table-column :align="'center'" label="校对时间" prop="checkTime" width="140"/>
          <el-table-column :align="'center'" label="校对护士" prop="checkNurseName" width="90"/>
          <el-table-column :align="'center'" label="执行护士" prop="executeNurseName" width="90"/>
          <el-table-column :align="'center'" label="医生停止时间" prop="stopInTime" width="140"/>
          <el-table-column :align="'center'" label="护士停止时间" prop="nurseStopTime" width="140"/>
          <el-table-column :align="'center'" label="停止护士" prop="stopNurseName" width="90"/>
          <el-table-column :align="'center'" label="皮试结果" prop="skinResult" width="90"/>
          <el-table-column :align="'center'" label="签名医生" prop="doctorSignature" width="90"/>
          <el-table-column :align="'center'" label="停止摆药" prop="dispStatus" width="70"/>
        </el-table>
      </el-form>
    </div>
    <div class="mr10" style="float: right;">我的患者</div>
    <el-dialog
      v-model="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :width="dialogWidth"
    >
      <exam-apply-form v-if="dialogType ==='4'" :inorout-flag="'1'" :org-id="userInfo.orgId"
                       :patient-id="patientId" :visit-id="visitId" @submit-form-ok="submitFormOk"/>
      <lab-apply-form v-if="dialogType ==='5'" :inorout-flag="'1'" :org-id="userInfo.orgId"
                      :patient-id="patientId" :visit-id="visitId" @submit-form-ok="submitFormOk"/>
      <prescription v-if="dialogType ==='6'" ref="prescriptionRef" :inorout-flag="'1'"
                    :patient-id="patientId" :visit-id="visitId" @submit-form-ok="submitFormOk"/>
      <orders-template v-if="dialogType ==='99'" ref="outpTreatRecTemplateTableRef" :is-quoted="true"
                       :org-id="userInfo.orgId" :storage-id="autoForm.storageId" @history-cancel="handleClose"/>
      <surgery-apply v-if="dialogType ==='7'" ref="surgeryApplyRef" :inorout-flag="'1'" :patient-info-this="patientInfo"/>
    </el-dialog>
  </div>

</template>

<script lang="ts" setup>
import {listDept} from '@/api/system/dept'
import {autoPrescriptionList} from "@/api/drug/drugStock.ts"
import {addOrders, delOrders, listOrders, updateOrderStatus} from "@/api/orders/orders.ts"
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {clinicTableHeadList, jsonStrInObj, prescriptionList} from "@/utils/autoComplete"
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts"
import examApplyForm from "@/views/doctor/exam/applyForm.vue"
import labApplyForm from "@/views/doctor/lab/applyForm.vue"
import prescription from "./visitPrescription/index.vue"
import {autoBuildQuery} from "@/api/base/clinicItemDict.ts";
import {useWebSocket} from "@/utils/useWebSocket.ts";
import OrdersTemplate from "@/views/template/wholeSet/ordersTemplate.vue";
import SurgeryApply from "@/views/surgery/apply/index.vue"

const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('order_status', 'billing_attr', 'order_type', 'new_order_type',
  'sys_yes_no', 'spec_unit', 'sys_drop_speed', 'drug_classification', 'dose_unit'))

const prescriptionRef = ref()
const surgeryApplyRef = ref()
// 弹出框状态
const dialogVisible = ref<boolean>(false)
// 弹出框内容类别
const dialogType = ref<string>("")
//弹出框标题
const dialogTitle = ref<string>("")
// 弹出框宽度
const dialogWidth = ref<string>("40%")
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(prescriptionList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])
// 创建一个ref数组来存储每个automatic-completion实例
const itemAutomaticRefs = ref<any[]>([]);

// 在模板中使用动态ref
function setItemAutomaticRef(el, index) {
  if (el) {
    itemAutomaticRefs.value[index] = el;
  }
}
const outpTreatRecTemplateTableRef = ref()

// 药房集合
const drugVsDeptList = ref<any>([])
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const formRef = ref()
const queryParams = ref<any>({
  repeatIncaditor: "",
  orderStatus: "22"
})

const ids = ref([]);
const selectionThis = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const orderClass = ref("1")
const deptList = ref<any[]>([])
const props = defineProps({
  visitId: {
    type: String,
    default: ""
  },
  patientId: {
    type: String,
    default: "",
  },
  hospitalNo: {
    type: String,
    default: "",
  },
  wardCode: {
    type: String,
    default: "",
  },

  patientInfo: {
    type: Object,
    default: () => {
    },
  }
})

const autoForm = ref<any>({
  drugClassArray: "",
  storageId: "",
  itemInfo: "",
  orgId: userInfo.orgId
})

const form = ref<any>({
  // 医嘱
  orderList: []
})

/**
 * 校验方法中通过rule获取对应行的orderClass
 * @param obj
 */
function ruleToOrderClass(obj: any) {
  const strArray = obj.field.split(".")
  let index = 0;
  if (strArray.length > 1) {
    index = strArray[1]
  }
  return form.value.orderList[index].orderClass
}

/**
 * 组号校验规则
 * @param rule
 * @param value
 * @param callback
 */
const groupNumberValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "组号不能为空"));
    }
    const pass = /^[0-9]\d*$/g.test(value);
    if (!pass) {
      callback(new Error(rule.message || "必须是正整数"));
    }
    callback();
  }
  callback();
}

/**
 * 频次选择框校验规则
 * @param rule
 * @param value
 * @param callback
 */
const performFreqValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "频次不能为空"));
    }
    callback();
  }
  callback();
}

/**
 * 途径选择框校验规则
 * @param rule
 * @param value
 * @param callback
 */
const channelValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "途径不能为空"));
    }
    callback();
  }
  callback();
}

/**
 * 单次用量校验规则
 * @param rule
 * @param value
 * @param callback
 */
const singleDoseValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "单次用量不能为空"));
    }
    callback();
  }
  callback();
}

/**
 * 数量校验规则
 * @param rule
 * @param value
 * @param callback
 */
const sumNumValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "数量不能为空"));
    }
    const pass = /^[0-9]\d*$/g.test(value);
    if (!pass) {
      callback(new Error(rule.message || "必须是正整数"));
    }
    callback();
  }
  callback();
}

/**
 * 医嘱内容校验规则
 * @param rule
 * @param value
 * @param callback
 */
const orderTextValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error(rule.message || "医嘱内容不能为空"));
  }
  callback();
}
// 表单校验
const rules = ref<any>({
  groupNumber: [
    {validator: groupNumberValidator, trigger: "change"}
  ],
  sumNum: [
    {validator: sumNumValidator, trigger: "change"}
  ],
  singleDosage: [
    {validator: singleDoseValidator, trigger: "change"}
  ],
  numSingle: [
    {validator: singleDoseValidator, message: "单次用量不能为空", trigger: "change"}
  ],
  orderText: [
    {validator: orderTextValidator, trigger: "change"}
  ],
  channel: [
    {validator: channelValidator, trigger: "change"}
  ],
  performFreq: [
    {validator: performFreqValidator, trigger: "change"}
  ],
})


function handleKeydown(event) {
  if (event.keyCode == "112") {
    // F1 新增医嘱
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddOrder()
  } else if (event.keyCode == "113") {
    // F2 开检查
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddExam()
  } else if (event.keyCode == "114") {
    // F3 开检验
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddLab()
  } else if (event.keyCode == "115") {
    // F4 开中草药
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddDrugChineseHerbalMedicine()
  } else if (event.keyCode == "116") {
    // F6 手术申请
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddSurgery()
  } else if (event.keyCode == "117") {
    // F7 耗材开单
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddMaterial()
  }
}

// 执行科室点击事件
function deptChange(event, index, row) {
  row.implementDept = event;
}

/** 途径点击事件 */
function administrationInfoChange(event, index, row) {
  row.channel = toRaw(event).dictValue
  alikeGroupNumberFun(row, index)
}

/** 频次选择事件 */
function performFreqInfoChange(event, index, row) {
  const performFreqInfo = toRaw(event)
  row.performFreq = performFreqInfo.freqId
  row.performFreqInfo = performFreqInfo
  row.nursePerformTime = performFreqInfo.performTime
  alikeGroupNumberFun(row, index)
  // calculatedQuantityAndMoney(index)

}

function admissionTimeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

/** 检查选择项目 */
function handleAddExam() {
  const orderListCount = form.value.orderList.length
  if (orderListCount > 0) {
    if (!form.value.orderList[orderListCount - 1].id) {
      return ElMessage.error("第" + orderListCount + "行数据还没有保存，请保存或者删除后再添加")
    }
  }
  dialogVisible.value = true
  dialogWidth.value = "40%"
  dialogType.value = "4"
}

/**
 * 检查检验开单保存后 子组件返回方法
 */
function submitFormOk() {
  handleClose()
  getList()
}

/**
 * 医嘱保存
 */
function saveOrder() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      ElMessageBox.confirm("确认要保存开单吗", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ordersList = form.value.orderList.filter((item: any) => {
          return item.orderClass != '4' && item.orderClass != '5' && item.orderStatus === "1"
        })
        if (ordersList.length <= 0) {
          ElMessage.error("没有需要保存的医嘱。")
        }
        const data = {
          "ordersList": ordersList,
          "orgId": userInfo.orgId,
          patientId: props.patientId,
          visitId: props.visitId,
        }
        // console.log("form.value.orderList",form.value.orderList)
        addOrders(data).then(() => {
          ElMessage.success("医嘱保存成功")
          // // 新建websocket 长链接
          // useWebSocket.connect(`ws://127.0.0.1:9004/businessws/websocket/orders`);
          form.value.orderList = []
          getList()
          // form.value.orderList.splice(form.value.orderList.length - 1, 1)
          // handleAddOrder()
        })
      }).catch(() => {
        ElMessage.info("取消操作");
      });
    }
  })
}

/**
 * 传输医嘱
 */
function transmitOrder() {
  initSelectionThis("", "1")
  if (ids.value.length <= 0) {
    return ElMessage.error("没有【新开】状态的医嘱，请勾选需要传输的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要传输医嘱吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "2",
      wardCode: props.wardCode,
      orgId: userInfo.orgId
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("传输成功")
      // 发送信息
      const param = {
        "orgId": userInfo.orgId,
        "type": "transmitOrder",
        "wardCode": props.wardCode,
        "orderStatus": "2",
        "userId": userInfo.userId
      }
      useWebSocket.sendMessage(JSON.stringify(param));
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 作废医嘱
 */
function cancelOrder() {
  selectionThis.value = selectionThis.value.filter((item: any) => item.orderStatus === '1' || item.orderStatus === '2')
  ids.value = selectionThis.value.map((item: any) => item.id);
  if (ids.value.length <= 0) {
    return ElMessage.error("只能作废【传输】【转抄】状态的医嘱，没有符合上述状态的医嘱，请重新勾选需要作废的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要作废医嘱吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "6"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("作废成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 停止医嘱
 */
function stopOrder() {
  initSelectionThis("0", "7")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【校对】状态的【长期】医嘱，请勾选医嘱状态为【校对】状态的【长期】医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【长嘱停止】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "9"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("长嘱停止成功")
      getList()
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 组织多选功能 向后台传递的ids
 * @param repeatIncaditor 长期/临时
 * @param type 医嘱状态
 */
function initSelectionThis(repeatIncaditor: string, type: string) {
  selectionThis.value = selectionThis.value.filter((item: any) => item.orderStatus === type)
  // type = 07（校对状态的长期医嘱） （获取状态为校对的长期医嘱）
  if (repeatIncaditor + type === '07') {
    selectionThis.value = selectionThis.value.filter((item: any) => item.repeatIncaditor === '0')
  }
  // type = 17（校对状态的临时医嘱） （获取状态为校对的临时医嘱）
  if (repeatIncaditor + type === '17') {
    selectionThis.value = selectionThis.value.filter((item: any) => item.repeatIncaditor === '1')
  }
  ids.value = selectionThis.value.map((item: any) => item.id);
}

/** 检验选择项目 */
function handleAddLab() {
  const orderListCount = form.value.orderList.length
  if (orderListCount > 0) {
    if (!form.value.orderList[orderListCount - 1].id) {
      return ElMessage.error("第" + orderListCount + "行数据还没有保存，请保存或者删除后再添加")
    }
  }
  dialogVisible.value = true
  dialogWidth.value = "40%"
  dialogType.value = "5"
}

/**长/临 选择事件 */
function repeatIncaditorChange(event, index, row) {
  alikeGroupNumberFun(row, index)
  if (row.repeatIncaditor === "0") {
    row.firstDayIsDisp = "Y"
    calculatedQuantityAndMoney(index)
  } else {
    row.firstDayIsDisp = "N"
    row.firstDayDrugDispAmount = 0
  }
}


/* 执行时间 改变事件*/
function nursePerformTimeBlur(event, index, row) {
  alikeGroupNumberFun(row, index)
}

/* 下达时间 改变事件*/
function createTimeChange(event, index, row) {
  alikeGroupNumberFun(row, index)
}

/**
 * 组号改变事件
 */
function groupNumberBlur(_event, index: number, row: any) {
  if (form.value.orderList.length > 1) {
    // 获取当前行 行号
    const currentGroupNumber = row.groupNumber
    // 获取当前行的上一行数据
    const previousRow = form.value.orderList[index - 1]
    const previousGroupNumber = previousRow.groupNumber
    if (currentGroupNumber != null && currentGroupNumber == previousGroupNumber) {
      row.createTime = previousRow.createTime
      row.orderClass = previousRow.orderClass
      row.repeatIncaditor = previousRow.repeatIncaditor
      row.channel = previousRow.channel
      row.performFreq = previousRow.performFreq
      row.nursePerformTime = previousRow.nursePerformTime
      row.performFreqInfo = previousRow.performFreqInfo
    }
  }
}

/**首日是否摆药 选择事件 */
function firstDayIsDispChange(event, index, row) {
  if (row.firstDayIsDisp === "Y") {
    calculatedQuantityAndMoney(index)
  } else {
    row.firstDayDrugDispAmount = 0
  }
}

/**
 * 相同组号修改 事件
 */
function alikeGroupNumberFun(row: any, index: number) {
  // const groupNumber = row.groupNumber.replace(" ", "")
  const groupNumber = row.groupNumber
  if (groupNumber != "") {
    // 获取与当前行 组号相同的数据的下标 返回数组
    const alikeGroupNumberIndexArray = proxy.$getAllIndices(form.value.orderList, row.groupNumber, "groupNumber");
    alikeGroupNumberIndexArray.forEach((index: number) => {
      if (form.value.orderList[index].orderClass === '1' && (form.value.orderList[index].orderStatus === '1' || form.value.orderList[index].orderStatus === '2')) {
        form.value.orderList[index].createTime = row.createTime
        form.value.orderList[index].orderClass = row.orderClass
        form.value.orderList[index].repeatIncaditor = row.repeatIncaditor
        form.value.orderList[index].channel = row.channel
        form.value.orderList[index].performFreq = row.performFreq
        form.value.orderList[index].nursePerformTime = row.nursePerformTime
        form.value.orderList[index].performFreqInfo = row.performFreqInfo
      }
      calculatedQuantityAndMoney(index)
    })
  } else {
    // 组号为空
    calculatedQuantityAndMoney(index)
  }
}

/** 新开医嘱类别事件 */
function orderClassChange(_event, index, row) {
  tableBodyList.value = []
  if (row.orderClass === "1" || row.orderClass === "6") {
    tableHeadList.value = jsonStrInObj(prescriptionList)
    //药品 、出院带药
    form.value.orderList[index].performFreqDisabled = false
    form.value.orderList[index].firstDayDrugDispAmountDisabled = false
    form.value.orderList[index].singleDoseDisabled = false
    form.value.orderList[index].singleDosageDisabled = false
    form.value.orderList[index].dripSpeedDisabled = false
    form.value.orderList[index].numSingleDisabled = false
    form.value.orderList[index].nursePerformTimeDisabled = false
    form.value.orderList[index].implementDeptDisabled = false
    form.value.orderList[index].remarksDisabled = false
    form.value.orderList[index].createTimeDisabled = false
    form.value.orderList[index].groupNumberDisabled = false
    form.value.orderList[index].repeatIncaditorDisabled = false
    form.value.orderList[index].isMedicalDisabled = false
    form.value.orderList[index].billingAttrDisabled = false
    form.value.orderList[index].performFreq = row.performFreq || ""
    form.value.orderList[index].channel = row.channel || ""
    form.value.orderList[index].singleDosage = row.singleDosage || ""
    form.value.orderList[index].numSingle = row.numSingle || ""
    form.value.orderList[index].sumNum = row.sumNum || "0"
    form.value.orderList[index].firstDayDrugDispAmount = row.firstDayDrugDispAmount || "0"
    // 如果是出院带药，是否计价设置为 不计价 ，如果是正常药品的设置为 正常计价
    form.value.orderList[index].billingAttr = row.orderClass === "1" ? "1" : "2"
  } else if (row.orderClass === "2") {
    tableHeadList.value = jsonStrInObj(clinicTableHeadList)
    //非药品
    form.value.orderList[index].performFreqDisabled = false
    form.value.orderList[index].firstDayDrugDispAmountDisabled = true
    form.value.orderList[index].singleDoseDisabled = true
    form.value.orderList[index].singleDosageDisabled = true
    form.value.orderList[index].dripSpeedDisabled = true
    form.value.orderList[index].numSingleDisabled = true
    form.value.orderList[index].nursePerformTimeDisabled = false
    form.value.orderList[index].implementDeptDisabled = false
    form.value.orderList[index].remarksDisabled = true
    form.value.orderList[index].createTimeDisabled = false
    form.value.orderList[index].groupNumberDisabled = true
    form.value.orderList[index].repeatIncaditorDisabled = false
    form.value.orderList[index].isMedicalDisabled = true
    form.value.orderList[index].billingAttrDisabled = false
    form.value.orderList[index].performFreq = row.performFreq || " "
    form.value.orderList[index].channel = row.channel || " "
    form.value.orderList[index].singleDosage = row.singleDosage || " "
    form.value.orderList[index].nursePerformTime = row.nursePerformTime || " "
    form.value.orderList[index].numSingle = row.numSingle || " "
    form.value.orderList[index].groupNumber = ""
    form.value.orderList[index].sumNum = row.sumNum || "1"
    form.value.orderList[index].firstDayDrugDispAmount = 0
    form.value.orderList[index].billingAttr = "1"
  } else if (row.orderClass === "3") {
    //嘱托
    form.value.orderList[index].performFreqDisabled = false
    form.value.orderList[index].firstDayDrugDispAmountDisabled = true
    form.value.orderList[index].channelDisabled = false
    form.value.orderList[index].singleDoseDisabled = true
    form.value.orderList[index].singleDosageDisabled = true
    form.value.orderList[index].dripSpeedDisabled = true
    form.value.orderList[index].numSingleDisabled = true
    form.value.orderList[index].nursePerformTimeDisabled = false
    form.value.orderList[index].implementDeptDisabled = false
    form.value.orderList[index].remarksDisabled = true
    form.value.orderList[index].createTimeDisabled = false
    form.value.orderList[index].groupNumberDisabled = true
    form.value.orderList[index].billingAttrDisabled = true
    form.value.orderList[index].repeatIncaditorDisabled = false
    form.value.orderList[index].isMedicalDisabled = true
    form.value.orderList[index].performFreq = row.performFreq || ""
    form.value.orderList[index].nursePerformTime = row.nursePerformTime || ""
    form.value.orderList[index].channel = row.channel || ""
    form.value.orderList[index].groupNumber = ""
    form.value.orderList[index].billingAttr = "2"
    form.value.orderList[index].firstDayDrugDispAmount = 0
  } else if (row.orderClass === "4") {
    //检查
    colDisabled(index, row)
  } else {
    // 检验
    colDisabled(index, row)
  }
}

/**
 * 医嘱列表禁用
 * @param index
 * @param row
 */
function colDisabled(index: number, row: any) {
  form.value.orderList[index].performFreqDisabled = true
  form.value.orderList[index].singleDoseDisabled = true
  form.value.orderList[index].singleDosageDisabled = true
  form.value.orderList[index].channelDisabled = true
  form.value.orderList[index].sumNumDisabled = true
  form.value.orderList[index].firstDayDrugDispAmountDisabled = true
  form.value.orderList[index].dripSpeedDisabled = true
  form.value.orderList[index].numSingleDisabled = true
  form.value.orderList[index].nursePerformTimeDisabled = true
  form.value.orderList[index].groupNumberDisabled = true
  form.value.orderList[index].implementDeptDisabled = true
  form.value.orderList[index].repeatIncaditorDisabled = true
  form.value.orderList[index].billingAttrDisabled = true
  form.value.orderList[index].remarksDisabled = true
  form.value.orderList[index].createTimeDisabled = true
  form.value.orderList[index].isMedicalDisabled = true
  form.value.orderList[index].performFreq = row.performFreq || " "
  form.value.orderList[index].singleDosage = row.singleDosage || ""
  form.value.orderList[index].nursePerformTime = row.nursePerformTime || ""
  form.value.orderList[index].numSingle = row.numSingle || ""
  form.value.orderList[index].billingAttr = "2"
}

/**
 * dialog关闭事件
 */
function handleClose() {
  dialogType.value = ""
  dialogVisible.value = false
  getList()
}


/**
 * 滴速点击事件
 */
function dripSpeedChange(e, _index: number, row: any) {
  const sysDropSpeedArr: any = toRaw(dictDataMap.value['sys_drop_speed'])
  const indexNum = sysDropSpeedArr.findIndex((sysDropSpeed: any) => {
    return sysDropSpeed.dictValue === e
  })
  if (indexNum > -1) {
    if (row.remarks) {
      let str = row.remarks + "," + sysDropSpeedArr[indexNum].dictLabel
      row.remarks = str;
    } else {
      row.remarks = sysDropSpeedArr[indexNum].dictLabel
    }
  }
}

/**
 * 开中草药
 */
function handleAddDrugChineseHerbalMedicine() {
  const orderListCount = form.value.orderList.length
  if (orderListCount > 0) {
    if (!form.value.orderList[orderListCount - 1].id) {
      return ElMessage.error("第" + orderListCount + "行数据还没有保存，请保存或者删除后再添加")
    }
  }
  dialogVisible.value = true
  dialogWidth.value = "90%"
  dialogType.value = "6"
  nextTick(() => {
    prescriptionRef.value.getList()
  })
}

/**
 * 新增手术
 */
function handleAddSurgery() {
  const orderListCount = form.value.orderList.length
  if (orderListCount > 0) {
    if (!form.value.orderList[orderListCount - 1].id) {
      return ElMessage.error("第" + orderListCount + "行数据还没有保存，请保存或者删除后再添加")
    }
  }
  dialogType.value = "7"
  dialogVisible.value = true
  dialogWidth.value = "80%"
}

/**
 * 新增医嘱
 */
function handleAddOrder() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      // 最大的组号
      let maxGroupNumber = 0
      if (form.value.orderList.length > 0) {
        // 获取表格内最大的组号
        maxGroupNumber = Math.max.apply(Math, form.value.orderList.map((item: any) => {
          return item.groupNumber
        }))
      }
      // 重置医嘱类别
      orderClass.value = "1"
      form.value.orderList.push({
        visitId: proxy.visitId,
        patientId: proxy.patientId,
        orderClass: "1",
        orderStatus: "1",
        billingAttr: "1",
        repeatIncaditor: "1",
        firstDayIsDisp: "N",
        isMedical: "Y",
        price: 0.00,
        groupNumber: maxGroupNumber + 1,
        orderText: "",
        sumNum: "",
        firstDayDrugDispAmount: 0,
        numSingle: "",
        isShow: true,
        isAutoShow: false,
        createTime: proxy.$parseTime(new Date()),
        implementDept: currentSelectDept,
        // 途径是否禁用
        channelDisabled: false,
        // 频次是否禁用
        performFreqDisabled: false,
        // 单次用量是否禁用
        singleDoseDisabled: false,
        // 数量是否禁用
        sumNumDisabled: false,
        //首日摆药数量
        firstDayDrugDispAmountDisabled: false,
        // 滴速是否禁用
        dripSpeedDisabled: false,
        // 单次用量是否禁用
        numSingleDisabled: false,
        // 护士执行时间是否禁用
        nursePerformTimeDisabled: false,
        // 组号是否禁用
        groupNumberDisabled: false,
        // 执行科室是否禁用
        implementDeptDisabled: false,
        // 下达时间是否禁用
        createTimeDisabled: false,
        // 医生说明是否禁用
        remarksDisabled: false,
        // 是否计价是否禁用
        billingAttrDisabled: false,
        // 长/临是否禁用
        repeatIncaditorDisabled: false
      })
      nextTick(() => {
        initInputDOM(form.value.orderList.length - 1);
      });
    }
  })
}

function initInputDOM(index) {
  //获取id为table-form下的所有input 框
  const inputDoms = document.querySelectorAll(
    ".groupNumber .el-input__inner"
  )
  inputDoms[index].focus();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectionThis.value = selection
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 删除 */
function handleDelete(index: number, row: any) {
  ElMessageBox.confirm('删除后数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    if (!row.id) {
      form.value.orderList.splice(Number(index), 1)
    } else {
      const idsThis = row.id || ids.value;
      delOrders(idsThis).then(() => {
        form.value.orderList.splice(Number(index), 1)
      })
    }
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}


/** 项目名称自动补全检索 */
function itemNameInput(event: any, index, row) {
  autoForm.value.itemInfo = event
  if (row.orderClass === "1" || row.orderClass === "6") {
    tableHeadList.value = jsonStrInObj(prescriptionList)
    getListDrugItem(row,index)
  } else if (row.orderClass === "2") {
    tableHeadList.value = jsonStrInObj(clinicTableHeadList)
    getListClinicItemDict(index)
  }

}

/** 自动补全后台查询非药品 */
function getListClinicItemDict(index:number) {
  if (autoForm.value.itemInfo) {
    autoForm.value.notInSelect = ['A', 'B', 'C', 'D', 'F', 'J', 'K', 'L']
    // 是否过滤已存在的项目标记
    autoForm.value.isFiltrationContrastExist = true
    autoBuildQuery(autoForm.value).then(res => {
      tableBodyList.value = res.data
      // 打开自动补全弹出框
      itemAutomaticRefs.value[index].init()
    })
  } else {
    tableBodyList.value = []
  }
}

/** 自动补全后台查询药品 */
function getListDrugItem(row,index:number) {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = userInfo.orgId
    autoPrescriptionList(autoForm.value).then(res => {
      let data = res.data
      // 打开自动补全弹出框
      itemAutomaticRefs.value[index].init()
      if (row.repeatIncaditor === '0') {
        // 长期
        tableBodyList.value = data.filter(item => item.packSize === "1" || item.packageNum === 1)
      } else {
        //临时
        tableBodyList.value = data
      }
    })
  } else {
    tableBodyList.value = []
  }
}

/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  itemAutomaticRefs.value[index].setItemName(e.itemName || e.drugName)
  itemAutomaticRefs.value[index].closePopover()
  row.isShow = true
  row.isAutoShow = false
  row.doseUnits = e.doseUnits
  row.singleDosage = e.dose
  row.singleDosageMin = e.dose
  let drugClass = ""
  if (e.drugClass === "1" || e.drugClass === "2") {
    drugClass = "A"
  } else {
    drugClass = "B"
  }
  row.itemClass = e.itemClass || drugClass
  row.doseUnitsName = e.doseUnitsName
  if (!row.channel) {
    row.channel = e.channel
  }
  if (!row.performFreq) {
    row.performFreq = e.performFreq
    row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
    row.nursePerformTime = dictStore.getAppointPerformFreqInfo(e.performFreq).performTime
  }
  row.packageSpec = e.packageSpec || e.itemSpec
  row.clinicItemId = e.drugPriceId || e.clinicItemId
  row.identicalInfoId = e.identicalInfoId
  row.minUnits = e.minUnits
  row.minUnitsName = e.minUnitsName
  row.minSpec = e.minSpec
  row.packageUnits = e.packageUnits
  row.packSize = e.packSize
  row.singleUnit = e.doseUnits
  row.unitsName = e.unitsName
  // 发药药房
  row.storageId = e.storageId
  row.packageNum = e.packageNum
  row.packageNumCalculate = e.packSize === "1" ? 1 : e.packageNum || 1
  row.drugInfoId = e.drugInfoId
  row.orderText = e.drugName || e.itemName
  row.price = e.price || e.subTotal
  row.quantityAndUnits = e.quantityAndUnits
  // row.implementDept = e.storageId
  row.sort = index + 1
  inputBlur(index)
  tableBodyList.value = []
}

/**
 * 单次剂量input失去焦点事件
 */
function inputBlur(index: number) {
  calculatedQuantityAndMoney(index)
}


/**
 * 计算数量 和金额
 */
function calculatedQuantityAndMoney(index: number) {
  const orderClassThis = form.value.orderList[index].orderClass
  // 最小剂量
  const singleDosageMin = form.value.orderList[index].singleDosageMin
  // 单次剂量（不用做计算）
  const singleDosage = form.value.orderList[index].singleDosage
  // 单次用量 实际开出剂量
  let numSingle = 0
  // 包装数量
  let packageNumCalculate = 1
  // 医嘱类别药品、非药品、嘱托  1: 药品
  if (orderClassThis === "1") {
    numSingle = form.value.orderList[index].numSingle || 1
    packageNumCalculate = form.value.orderList[index].packageNum
  } else {
    numSingle = 1
    packageNumCalculate = 1
  }
  if (typeof numSingle !== "undefined" && typeof packageNumCalculate !== "undefined") {
    let performTime: number = 1;
    // 获取频次对应的服用次数
    if (toRaw(form.value.orderList[index].performFreqInfo) !== undefined && toRaw(form.value.orderList[index].performFreqInfo).performTime !== undefined
      && toRaw(form.value.orderList[index].performFreqInfo).performTime) {
      performTime = form.value.orderList[index].performFreqInfo ?
        form.value.orderList[index].performFreqInfo.performTime.split("-").length : 1
    }
    // 计算实际开出的单次用量和最小剂量的商
    // const num: number = Number(Math.ceil(singleDosage / singleDosageMin))
    const num: number = Number(numSingle)
    const amount: number = Number(Math.ceil(performTime * num))
    // 计算实际开出的单次用量和最小剂量的商
    const packSize = form.value.orderList[index].packSize
    // 列表中总数量
    let sumNum: number = 0
    if (packSize === "1") {
      // 小包装
      sumNum = amount
    } else {
      // 大包装
      sumNum = Number(Math.ceil(amount / packageNumCalculate))
    }
    // 给总数量赋值
    form.value.orderList[index].sumNum = sumNum
    if (form.value.orderList[index].repeatIncaditor === '0') {
      //首日摆药数量
      form.value.orderList[index].firstDayDrugDispAmount = amount
    } else {
      //首日摆药数量
      form.value.orderList[index].firstDayDrugDispAmount = 0
    }
    // // 给总价赋值
    // form.value.orderList[index].sumPrice = Number((sumAmount * form.value.orderList[index].price).toFixed(2))
  }
}


// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: currentSelectDept,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("1,2", ","),
    storageTypeArray: proxy.$stringToArray("3,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("2", ","),
    storageClassArray: proxy.$stringToArray("2,3", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    if (!res.data) {
      return ElMessage.error("本科室未绑定摆药药房，无法开药品医嘱，请联系药房人员添加后再开药。")
    }
    drugVsDeptList.value = res.data
    prescriptionTypeChange()
  })
}


function prescriptionTypeChange() {
  // 西药
  autoForm.value.drugClass = "A"
  autoForm.value.storageId = drugVsDeptList.value[0].id
  autoForm.value.prescAttr = "1"
  autoForm.value.drugClassArray = drugVsDeptList.value[0].drugClass.split(",")
}

function handleQuery() {
  getList()
}

//电子病历单点登录
function emrURL() {
  //链接跳转
  const emrURL = 'http://123.139.118.82:9000' //临时写法
  let url = `${emrURL}/emrcloud/showRecord/transfer?from=his&name=InpMedRecordEditor&orgId=${userInfo.orgId}&patientRegId=${props.visitId}&userId=${userInfo.userId}&currentDeptAreaId=${currentSelectDept}&p1=his&p2=his`
  window.open(url, "_blank")
}

function getList() {
  const param = {
    orgId: userInfo.orgId,
    visitId: props.visitId,
    orderText: queryParams.value.orderText,
    repeatIncaditor: queryParams.value.repeatIncaditor,
    orderStatus: queryParams.value.orderStatus === '22' ? '' : queryParams.value.orderStatus,
  }
  listOrders(proxy.$addDateRange(param, dateRange.value)).then((res: resType) => {
    let unSave = form.value.orderList.filter(e => e.id == null)
    form.value.orderList = []
    const data: any = res.data
    data.forEach((item: any, index) => {
      item.itemId = ""
      item.isShow = !(item.orderStatus != "1" || item.orderText.includes("中草药"));
      // 设置药品或者非药品显示自动补全组件
      item.isAutoShow = !(item.orderClass === '1' || item.orderClass === '2');

      // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
      // item.noSkin = trDisabled.value === true ? item.noSkin === "Y" : item.noSkin
      item.doseUnitsName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.doseUnits).dictLabel
      const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
      item.unit = unit
      item.unitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
      item.minUnitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], item.minUnits).dictLabel
      item.orderClassDisabled = item.orderClass === '4' || item.orderClass === '5'
      let price: number = 0;
      if (item.ordersCostVoList != null) {
        item.ordersCostVoList.forEach(orderCost => {
          price += Number(orderCost.price)
        })
      }
      item.price = price
      // 自动补全组件赋值
      nextTick(()=>{
        if (itemAutomaticRefs.value[index]) {
          itemAutomaticRefs.value[index].setItemName(item.orderText)
        }
      })
      form.value.orderList.push(item)
      orderClassChange(null, index, item)
    })
    form.value.orderList = form.value.orderList.concat(unSave)
    unSave = []
  })
}

// 获取科室集合
function getDeptList() {
  let queryParams = {
    orgId: userInfo.orgId
  }
  listDept(queryParams).then(res => {
    deptList.value = res.data
  })
}

/**
 * 模板引用
 */
function templateOpen() {
  dialogType.value = "99"
  dialogVisible.value = true
  dialogWidth.value = "90%"
}

getDeptList()
getDrugVsDeptListFun()
getList()


// 组件挂载时添加事件监听
onMounted(() => {
  useWebSocket.connect(`ws://127.0.0.1:9004/businessws/websocket/orders`);
  window.addEventListener('keydown',
    handleKeydown);
});
// 组件卸载时移除事件监听以避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('keydown',
    handleKeydown);
});

defineExpose({
  getList
})
</script>

<style lang="scss" scoped>

.yizhu-table {
  .el-form-item--small {
    margin-bottom: 0 !important;
  }

  .el-form-item {
    margin-bottom: 0 !important;
    padding: 8px 0;
  }

  .el-form-item__content {
    margin-bottom: 0 !important;
  }

  .el-table__cell {
    margin-bottom: 0 !important;
    border-bottom: none !important;
  }

  .el-table td.el-table__cell div {
    margin-bottom: 0 !important;
  }
}

.app-container {
  .header-button-primary {
    width: 64px;
    height: 24px;
    background: #4E64F6 !important;
    border-radius: 17px;
  }

  .header-button-warning {
    width: 76px;
    height: 24px;
    background: #349D5F !important;
    border-radius: 17px;
  }

  .app-container-table-list {
    margin-top: 20px;
    width: 200%;
    margin-left: -100%;
  }

  @media screen and (max-width: 1919.98px) {
    .app-container-table-list {
      width: 152%;
      margin-left: -53%;
    }
  }
}

:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: -15px;
}

:deep(.el-form-item__content) {
  margin-bottom: 6px;
}

:deep(.el-form-item__error) {
  font-size: 11px;
  color: #ff0000;
}

:deep(.el-button--small) {
  --el-button-size: 20px;
}

:deep(.el-table__body tr.current-row>td>div>button>span ) {
  color: #000000 !important;
}


</style>
